package CAS.AtomicStampedReference;

import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStamptedReferenceDemo {
    // 初始值：19        初始时间戳：0
    static AtomicStampedReference<Integer> atomicReference = new AtomicStampedReference<>(19, 0);

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            int stamp = atomicReference.getStamp();//
            new Thread(() -> {
                while (true) {
                    while (true) {
                        Integer money = atomicReference.getReference();
                        if (money < 20) {
                            if (atomicReference.compareAndSet(money, money + 20, stamp, stamp + 1)) {
                                System.out.println("金额小于20，充值了20元,余额： " + atomicReference.getReference());
                                break;
                            } else {
                                System.out.println("金额小于20，但是标签变了，说明之前已经充值过了！");
                            }
                        } else {
                            System.out.println("金额大于20，不需要充值");
                        }
                    }
                }
            }).start();
        }//for

        new Thread(() -> {
            while (true) {  // 让100个消费动作，一直消费
                Integer money = atomicReference.getReference();
                int stamp = atomicReference.getStamp();
                if (atomicReference.compareAndSet(money, money - 10, stamp, stamp + 1)) {
                    System.out.println("消费10元,余额： " + atomicReference.getReference());
                } else {
                    System.out.println("金额不够20元，不能消费");
                }
            }
        }).start();
    }


}
